package sendMail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

public class SendMail {
	private String host = "smtp.163.com";
	private String user = "javamailtesttj@163.com";
	private String password = "123456tj";
	
	private String from;
	private String to;
	private String subject;
	private String bodyText;
	
	
	

	public SendMail(String from, String to, String subject, String bodyText) {
		super();
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.bodyText = bodyText;
	}
	
	public void send(){
		Properties properties =new Properties();    //设置属性
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.auth", "true");
		Session session = Session.getInstance(properties); //创建会话
		session.setDebug(true);
		MimeMessage mimeMessage = new MimeMessage(session);  //创建邮件
		try{
			mimeMessage.setFrom(new InternetAddress(from));   //设置邮件发出者
			mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
			mimeMessage.setSubject(subject);
			BodyPart bodyPart = new MimeBodyPart(); 
			BodyPart bodyPartMessage = new MimeBodyPart();//创建正文
			bodyPartMessage.setText(bodyText);
			//添加附件
			DataSource ds = new FileDataSource("e://幽默.wmv");    //创建数据源
			bodyPart.setDataHandler(new DataHandler(ds));          //将数据源添加到邮件中
			bodyPart.setFileName(MimeUtility.encodeText(ds.getName())); //防止附件名乱码
			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(bodyPartMessage);
			multipart.addBodyPart(bodyPart);
			mimeMessage.setContent(multipart);                   //添加邮件至MimeMessage中
			mimeMessage.saveChanges();
			Transport transport = session.getTransport("smtp");  //创建连接
			transport.connect(host, user, password);
			transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());  //发送邮件
			transport.close();                                  //关闭连接
		}catch(Exception e){
			e.printStackTrace();
		}
	}




	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SendMail sendMail = new SendMail("javamailtesttj@163.com","javamailtesttj@163.com","TestMail","Hello word!");
		sendMail.send();

	}

}
